package com.taxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxx.entity.SysPermission;
import com.taxx.mapper.SysPermissionMapper;
import com.taxx.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统权限服务实现类
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public List<SysPermission> getPermissionList() {
        return permissionMapper.selectEnabledPermissions();
    }

    @Override
    public SysPermission getPermissionById(Long id) {
        return getById(id);
    }

    @Override
    public boolean createPermission(SysPermission permission) {
        // 检查权限编码是否已存在
        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("permission_code", permission.getPermissionCode());
        if (count(wrapper) > 0) {
            throw new RuntimeException("权限编码已存在");
        }

        permission.setStatus(1); // 默认启用
        return save(permission);
    }

    @Override
    public boolean updatePermission(SysPermission permission) {
        // 检查权限编码是否已被其他权限使用
        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
        wrapper.eq("permission_code", permission.getPermissionCode())
                .ne("id", permission.getId());
        if (count(wrapper) > 0) {
            throw new RuntimeException("权限编码已存在");
        }

        return updateById(permission);
    }

    @Override
    public boolean deletePermission(Long id) {
        // 检查权限是否被角色使用
        // 这里可以添加检查逻辑，如果权限被使用则不允许删除
        return removeById(id);
    }

    @Override
    public boolean updatePermissionStatus(Long id, Integer status) {
        SysPermission permission = new SysPermission();
        permission.setId(id);
        permission.setStatus(status);
        return updateById(permission);
    }

    @Override
    public List<SysPermission> getPermissionsByRoleId(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Long userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }
    
    @Override
    public List<SysPermission> getPermissionsByUsername(String username) {
        return permissionMapper.selectPermissionsByUsername(username);
    }
}
